<template>
  <div class="page">
    <h4>购物车</h4>
    <table>
      <tr>
        <th>勾选</th>
        <th>课程名称</th>
        <th>课程价格</th>
        <th>数量</th>
        <th>价格</th>
      </tr>
      <tr v-for="(item,index) in cartData" :key="index">
        <td>
          <input type="checkbox" v-model="item.isActive" />
        </td>
        <td>{{item.name}}</td>
        <td>{{item.price}}</td>
        <td>
          <button @click="minusCount(index)">-</button>
          {{item.number}}
          <button @click="addCount(index)">+</button>
        </td>
        <td>{{item.price}}</td>
      </tr>
      <tr>
        <td></td>
        <td colspan="2">{{checkedCount}}/{{allCount}}</td>
        <td>{{allNumber}}</td>
        <td>{{allPrice}}</td>
      </tr>
    </table>
  </div>
</template>

<script type="text/ecmascript-6">
export default {
  props: {
    cartData: {
      type: Array,
      default: []
    }
  },
  watch: {
    handler: {
      cartData(val) {
        //console.log(cartData);
      },
      deep: true
    }
  },
  data() {
    return {};
  },
  computed: {
    checkedCount: function() {
      let num = this.cartData.filter(o => o.isActive).length;
      return num;
    },
    allCount: function() {
      return this.cartData.length;
    },
    allNumber: function() {
      let num = 0;
      let arr = this.cartData.filter(o => o.isActive);
      arr.forEach(function(item) {
        num += item.number;
      });
      return num;
    },
    allPrice: function() {
      let price = 0;
      let arr = this.cartData.filter(o => o.isActive);
      arr.forEach(function(item) {
        price += item.number * item.price;
      });
      return price;
    }
  },
  methods: {
    minusCount(index) {
      if (this.cartData[index].number == 1) {
        if (window.confirm("确定要删除吗？")) {
          this.$emit("removeItem", index);
        }
      } else {
        this.cartData[index].number--;
      }
    },
    addCount(index) {
      this.cartData[index].number++;
    }
  },
  components: {}
};
</script>

<style scoped>
</style>
